#encoding:UTF-8
from tornado import ioloop, web
import tornado
import tornado.options
import mylib
import json
import MySQLdb

conn = mylib.create_conn()

class LogNewsHandler(web.RequestHandler):
    
    def gethostinfo(self):
        try:
            global conn
            result = []
            cmd = 'SELECT * FROM `tbl_host` WHERE `tbl_host`.`id` IN(70,80,59,61,64,81,57,82,74,83,62,86)'
            info = mylib.get_result_sql(conn,cmd)
            for i in info:
                buf = {}
                buf['id_host'] = i['id']
                buf['name_host'] = i['name']
                buf['link'] = i['module']
                buf['status'] = i['status']
                result.append(buf) 
            
            self.write(json.dumps(result))
            self.finish()
        except:
            out_put = {}
            out_put['error_code'] = 1
            out_put['msg'] = "Lỗi khác"
            self.write(out_put)
            self.finish()
            
            
    def getlogbysourcedate(self):
        try:
            global conn
            nguon = self.get_argument('id_host')
            ngay = self.get_argument('ngay')
            num = self.get_argument('num')
            get = self.get_argument('get')
            result = {}
            newbuf = []
            cmd = "CALL get_log_news_source_date('%s','%s','%s','%s')"%(nguon,ngay,num,get)
            count_str = "CALL get_count_news('%s','%s')"%(nguon,ngay)
            count_info = mylib.get_result_sql(conn,count_str)
            count = count_info[0]['count(i.id)']
            info = mylib.get_result_sql(conn,cmd)
            for i in info:
                buf = {}
                buf['id'] = i['id']
                buf['title'] = i['title']
                buf['timepost'] = i['timestamp']
                buf['urlimg'] = i['urlimg']
                buf['extract'] = i['extract']
                buf['hostname'] = i['hostname']
                buf['category'] = i['category']
                buf['url'] = i['url']
                newbuf.append(buf)
            result['total'] = count
            result['info'] = newbuf
            self.write(json.dumps(result))
            self.finish()
        except:
            out_put = {}
            out_put['error_code'] = 1
            out_put['msg'] = "Lỗi khác"
            self.write(out_put)
            self.finish()
    def getlogbydate(self):
        try:
            global conn
            ngay = self.get_argument('ngay')
            result = []
            for id in (70,80,59,61,64,81,57,82,74,83,62,86):
                
                cmd = "CALL get_log_news_date('%s','%s')"%(ngay,id)
                info = mylib.get_result_sql(conn,cmd)
                for i in info:
                    buf = {}
                    buf['host_id'] = id
                    buf['bao'] = i['name']
                    buf['hostname'] = i['module']
                    buf['total'] = i['COUNT(i.`id`)']
                    result.append(buf)
            self.write(json.dumps(result))
            self.finish()
        except:
            errorout = {}
            errorout['error_code'] = 1
            errorout['msg'] = 'Lỗi khác'
            self.write(json.dumps(errorout))
            self.finish()
    
    def getnewsdetail(self):
        try:
            global conn
            results = []
            id_news = self.get_arguments('id_news')
            cmd = "SELECT * FROM `tbl_items` WHERE `tbl_items`.`id` = " + str(int(id_news[0]))
            info = mylib.get_result_sql(conn,cmd)
            for i in info:
                buf = {}
                buf['id_news'] = id_news
                buf['id_host'] = i['hostid']
                buf['title'] = i['title']
                buf['extract'] = i['extract']
                buf['content'] = i['content']
                buf['temstring'] = i['temstring']
                buf['broad_time'] = i['timedate']
                buf['urlimg'] = i['urlimg']
                buf['hostname'] = i['hostname']
                buf['status'] = i['status']
                buf['category'] = i['category']
                buf['url'] = i['url']
                buf['get_time'] = mylib.get_datetime(int(i['timestamp']))
                buf['content_sm'] = i['content_sm']
                buf['tags'] = i['tags']
                buf['langid'] = i['langid']
                results.append(buf)
            self.write(json.dumps(results[0]))
            self.finish()
        except:
            errorout = {}
            errorout['error_code'] = 1
            errorout['msg'] = 'Lỗi khác'
            self.write(json.dumps(errorout))
            self.finish()
    
    def getlogintime(self):
        try:
            global conn
            current_date = mylib.get_timeunix_today()
            from_ngay = self.get_argument('from_date')
            from_unix = mylib.get_unixtime(from_ngay)
            to_ngay = self.get_argument('to_date')
            to_unix = mylib.get_unixtime(to_ngay)
            if from_unix > to_unix or from_unix > current_date or to_unix > current_date:
                errorout = {}
                errorout['error_code'] = 1
                errorout['msg'] = 'Bạn hãy kiểm tra lại ngày tháng!'
                self.write(json.dumps(errorout))
                self.finish()
            else:
                results = []
                for id_host in (70,80,59,61,64,81,57,82,74,83,62,86):
                    cmd = "CALL get_log_news_intime('%s','%s','%s')" %(id_host,from_ngay,to_ngay)
                    info = mylib.get_result_sql(conn, cmd)
                    for i in info:
                        buf = {}
                        buf['host_id'] = id_host
                        buf['bao'] = i['name']
                        buf['hostname'] = i['module']
                        buf['total'] = i['count(i.`id`)']
                        results.append(buf)
                self.write(json.dumps(results))
                self.finish()
        except:
            errorout = {}
            errorout['error_code'] = 1
            errorout['msg'] = 'Lỗi khác'
            self.write(json.dumps(errorout))
            self.finish()
                
                
    def get(self,path):
        if path.startswith('gethostinfo'):
            return self.gethostinfo()
        elif path.startswith('getlogbydate'):
            return self.getlogbydate()
        elif path.startswith('getlogbysourcedate'):
            return self.getlogbysourcedate()
        elif path.startswith('getlogintime'):
            return self.getlogintime()
        elif path.startswith('getnewsdetail'):
            return self.getnewsdetail()